package com.photographysharing.service.impl;

import com.photographysharing.exception.ServiceException;
import com.photographysharing.response.MessageResponse;
import com.photographysharing.service.MailService;
import jakarta.mail.MessagingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class MailServiceImpl  implements MailService {
    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String sendMailer;

    /**
     * 发送纯文本邮件
     * @param to
     * @param subject
     * @param text
     */
    public MessageResponse sendTextMailMessage(String to, String subject, String text){

        try {
            //true 代表支持复杂的类型
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(),true);
            //邮件发信人
            mimeMessageHelper.setFrom(sendMailer);
            //邮件收信人  1或多个
            mimeMessageHelper.setTo(to.split(","));
            //邮件主题
            mimeMessageHelper.setSubject(subject);
            //邮件内容
            mimeMessageHelper.setText(text);
            //邮件发送时间
            mimeMessageHelper.setSentDate(new Date());

            //发送邮件
            javaMailSender.send(mimeMessageHelper.getMimeMessage());
            return new MessageResponse("邮件发送成功!");

        } catch (MessagingException e) {
            e.printStackTrace();
            throw new ServiceException(200,"邮件发送失败!");
        }
    }
    /**
     * 发送邮箱验证码
     * @param to
     * @param code
     */
    public MessageResponse sendCodeMailMessage(String to, String code) {
        String subject = "邮箱验证码";
        String text = "验证码15分钟内有效:"+code;
        return sendTextMailMessage(to,subject,text);
    }


}
